package zxy_eatFood;

import java.awt.event.KeyEvent;
import java.util.ArrayList;

public class XYue {
    private ArrayList<Grid> body = new ArrayList<>();
    private int direction = KeyEvent.VK_DOWN;  // 默认方法是下

    Grid removedLast;

    /**
     * 潇月的初始组成
     * @return
     */
    public XYue(){
        body.add(new Grid(200,101));
        body.add(new Grid(200,91));
        body.add(new Grid(200,81));
        body.add(new Grid(200,71));
        body.add(new Grid(200,6));
        body.add(new Grid(200,51));
    }

    public ArrayList<Grid> getBody() {
        return body;
    }

    public void setBody(ArrayList<Grid> body) {
        this.body = body;
    }

    public int getDirection() {
        return direction;
    }

    public void setDirection(int direction) {
        // 如果键盘的方向和当前潇月的方向是相反的 那么就不用赋值给成员变量 潇月的方向保持不变
        if (this.direction == KeyEvent.VK_LEFT && direction == KeyEvent.VK_RIGHT) {
            return;
        } else if (this.direction == KeyEvent.VK_RIGHT && direction == KeyEvent.VK_LEFT) {
            return;
        } else if (this.direction == KeyEvent.VK_UP && direction == KeyEvent.VK_DOWN) {
            return;
        } else if (this.direction == KeyEvent.VK_DOWN && direction == KeyEvent.VK_UP) {
            return;
        }
        this.direction = direction;
    }

    /**
     * 潇月的移动
     */
    public void move(){
        Grid head = body.get(0);  //获取潇月的运动前端位置
        //判断潇月的朝向
        Grid newHead = null;
        switch (direction) {
            case KeyEvent.VK_LEFT:
                newHead = new Grid(head.getX() - 10, head.getY());
                break;
            case KeyEvent.VK_UP:
                newHead = new Grid(head.getX(), head.getY() - 10);
                break;
            case KeyEvent.VK_RIGHT:
                newHead = new Grid(head.getX() + 10, head.getY());
                break;
            case KeyEvent.VK_DOWN:
                newHead = new Grid(head.getX(), head.getY() + 10);
                break;
        }
        body.add(0, newHead);// 新的头部格子添加进来
        // 删除蛇的尾部, 返回尾部的对象 保存到成员变量
        removedLast = body.remove(body.size() - 1);
    }

    /**
     * 吃食物
     *
     * @param food
     * @return
     */
    public boolean eat(Grid food) {
        Grid head = body.get(0);// 蛇头
        if (head.getX() == food.getX() && head.getY() == food.getY()) {
            // 蛇头和食物坐标重合 说明吃到了
            body.add(removedLast);
            return true;
        }
        return false;
    }

    /**
     * 判断蛇是否撞墙 或者是否吃到自己身体
     *
     * @return
     */
    public boolean isDead() {

        Grid head = body.get(0);
        int x = head.getX();
        int y = head.getY();
        if (x < 0 || x >= 580 || y < 1 || y >= 361) {
            return true;
        }

        for (int i = 4; i < body.size(); i++) {
            Grid grid = body.get(i);
            if (x == grid.getX() && y == grid.getY()) {
                return true;
            }
        }
        return false;
    }
}
